package com.css.fxfzysx.modules.largeScreen.service.impl;

import com.css.fxfzysx.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzysx.base.attachment.service.AttachmentInfoService;
import com.css.fxfzysx.modules.largeScreen.param.ProbabilisticEarthquakeParam;
import com.css.fxfzysx.modules.largeScreen.repository.LargeScreenRepository;
import com.css.fxfzysx.modules.largeScreen.service.LargeScreenService;
import com.css.fxfzysx.modules.largeScreen.vo.CpvAnalysisVo;
import com.css.fxfzysx.modules.largeScreen.vo.CpvResultVo;
import com.css.fxfzysx.modules.largeScreen.vo.PeCurveVo;
import com.css.fxfzysx.modules.largeScreen.vo.ProbabilisticEarthquakeVo;
import com.css.fxfzysx.modules.lifeline.rest.JcsjRestManager;
import com.css.fxfzysx.modules.lifeline.rest.vo.CountyVo;
import com.css.fxfzysx.modules.vabStructure.param.EstimateParam;
import com.css.fxfzysx.modules.vabStructure.service.CustomVulnerabilityService;
import com.css.fxfzysx.modules.vabStructure.vo.BuildingVulnerabilityVo;
import com.css.fxfzysx.util.PlatformObjectUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LargeScreenServiceImpl implements LargeScreenService {

    @Autowired
    private LargeScreenRepository largeScreenRepository;

    @Autowired
    private JcsjRestManager jcsjRestManager;

    @Autowired
    private AttachmentInfoService attachmentInfoService;

    @Autowired
    private CustomVulnerabilityService customVulnerabilityService;

    @Override
    public HashMap<String, Object> getDestructiveState() throws Exception {
        //先获取全国的行政区划
        Map<String, Object> data = jcsjRestManager.getCountyName().getData();
        List<CountyVo> countyList = (List<CountyVo>) data.get("countyList");
        ObjectMapper mapper = new ObjectMapper();
        List<CountyVo> allCountyList = mapper.convertValue(countyList, new TypeReference<List<CountyVo>>() {
        });
        //建筑物格网中有数据的县
        List<String> countyNameList = (List<String>) data.get("countyNameList");

        //提取重复的
        List<CountyVo> duplicates = allCountyList.stream()
                .filter(countyVo -> countyNameList.contains(countyVo.getCounty()) && countyVo.getIntensity() != null)
                .collect(Collectors.toList());

        HashMap<String, Object> resultMap = new HashMap<>();
        //根据县去查数据
        for (CountyVo item : duplicates) {
            double six = 0.0;
            double seven = 0.0;
            double eight = 0.0;
            double nine = 0.0;
            double ten = 0.0;
            double sixProportion = 0.0;
            double sevenProportion = 0.0;
            double eightProportion = 0.0;
            double nineProportion = 0.0;
            double tenProportion = 0.0;
            Map<String, Object> areaMap = jcsjRestManager.getAreaByCountName(item.getCounty()).getData();
            Double steelratio = (Double) areaMap.get("steelratio");
            Double reconratio = (Double) areaMap.get("reconratio");
            Double brickratio = (Double) areaMap.get("brickratio");
            Double woodratio = (Double) areaMap.get("woodratio");
            Double otherratio = (Double) areaMap.get("otherratio");
            Double area = (Double) areaMap.get("area");
            //查县的易损性    矩阵
            List<EstimateParam> paramList = new ArrayList<>();
            EstimateParam param = new EstimateParam();
            param.setProvince(item.getProvince());
            param.setCity(item.getCity());
            param.setCounty(item.getCounty());
            paramList.add(param);
            List<BuildingVulnerabilityVo> list = (List<BuildingVulnerabilityVo>) customVulnerabilityService.getByRegion(paramList, item.getIntensity()).getData();
            Map<String, List<BuildingVulnerabilityVo>> collect = list.stream().collect(Collectors.groupingBy(BuildingVulnerabilityVo::getDestroy));
            HashMap<String, Object> map = new HashMap<>();
            for (Map.Entry<String, List<BuildingVulnerabilityVo>> entry : collect.entrySet()) {
                HashMap<String, Object> dataMap = new HashMap<>();
                for (BuildingVulnerabilityVo vo : entry.getValue()) {
                    Double value = 0.0;
                    switch (vo.getStructureType()) {
                        case 1:
                            value = steelratio;
                            break;
                        case 2:
                            value = reconratio;
                            break;
                        case 3:
                            value = brickratio;
                            break;
                        case 6:
                            value = woodratio;
                            break;
                        case 8:
                            value = otherratio;
                    }
                    six += value / area * vo.getSix().doubleValue();
                    seven += value / area * vo.getSeven().doubleValue();
                    eight += value / area * vo.getEight().doubleValue();
                    nine += value / area * vo.getNine().doubleValue();
                    ten += value / area * vo.getTen().doubleValue();

                    sixProportion += value * vo.getSix().doubleValue();
                    sevenProportion += value * vo.getSeven().doubleValue();
                    eightProportion += value * vo.getEight().doubleValue();
                    nineProportion += value * vo.getNine().doubleValue();
                    tenProportion += value * vo.getTen().doubleValue();
                }

                dataMap.put("sixProportion", sixProportion);
                dataMap.put("sevenProportion", sevenProportion);
                dataMap.put("eightProportion", eightProportion);
                dataMap.put("nineProportion", nineProportion);
                dataMap.put("tenProportion", tenProportion);

                dataMap.put("six", BigDecimal.valueOf(six).setScale(2, RoundingMode.HALF_UP));
                dataMap.put("seven", BigDecimal.valueOf(seven).setScale(2, RoundingMode.HALF_UP));
                dataMap.put("eight", BigDecimal.valueOf(eight).setScale(2, RoundingMode.HALF_UP));
                dataMap.put("nine", BigDecimal.valueOf(nine).setScale(2, RoundingMode.HALF_UP));
                dataMap.put("ten", BigDecimal.valueOf(ten).setScale(2, RoundingMode.HALF_UP));
                map.put(entry.getKey(), dataMap);
            }
            resultMap.put(item.getProvince() + "-" + item.getProvinceCode() + "-" + item.getCounty() + "-" + item.getCountyCode(), map);
        }
        return resultMap;
    }

    /**
     * 计算占比
     *
     * @param
     */
    public static Map<String, Object> calculatePercentages(double basically, double minor, double moderate, double serious, double collapse) {
        try {
            Map<String, Object> percentages = new HashMap<>();
            double total = basically + minor + moderate
                    + serious + collapse;
            if (total == 0) {
                return null;
            }
            percentages.put("basicallyProportion", BigDecimal.valueOf((basically / total) * 100).setScale(2, RoundingMode.HALF_UP));
            percentages.put("minorProportion", BigDecimal.valueOf((minor / total) * 100).setScale(2, RoundingMode.HALF_UP));
            percentages.put("moderateProportion", BigDecimal.valueOf((moderate / total) * 100).setScale(2, RoundingMode.HALF_UP));
            percentages.put("seriousProportion", BigDecimal.valueOf((serious / total) * 100).setScale(2, RoundingMode.HALF_UP));
            percentages.put("collapseProportion", BigDecimal.valueOf((collapse / total) * 100).setScale(2, RoundingMode.HALF_UP));
            String maxKey = "";
            BigDecimal maxValue = BigDecimal.ZERO;

            for (Map.Entry<String, Object> entry : percentages.entrySet()) {
                if (entry.getValue() instanceof BigDecimal) {
                    BigDecimal currentValue = (BigDecimal) entry.getValue();
                    if (currentValue.compareTo(maxValue) > 0) {
                        maxValue = currentValue;
                        maxKey = entry.getKey();
                    }
                }
            }
            percentages.put("max", maxKey);
            return percentages;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PeCurveVo getProbabilisticEarthquake(ProbabilisticEarthquakeParam param) {
        PeCurveVo peCurveVo = new PeCurveVo();
        ProbabilisticEarthquakeVo info = largeScreenRepository.getInfo(param);
        if (PlatformObjectUtils.isNotEmpty(info)) {
            if (PlatformObjectUtils.isNotEmpty(info.getSrvId())) {
                AttachmentInfoEntity attach = attachmentInfoService.getAttach(info.getSrvId());
                peCurveVo.setSrvPath(attach.getFileDirId() + attach.getAttachPath());
            }
            List<CpvAnalysisVo> list1 = largeScreenRepository.getCpvAnalysisEntityByCpviId(info.getCpviId());
            peCurveVo.setList1(list1);
            List<CpvResultVo> list2 = largeScreenRepository.getCpvResultEntityByCpviId(info.getCpviId());
            peCurveVo.setList2(list2);
        }
        return peCurveVo;
    }

    @Override
    public void getCompleteness() throws Exception {
        Map<String, Object> data = jcsjRestManager.getComplete().getData();
        data.forEach((k, v) -> {
            HashMap<String, Object> map = (HashMap<String, Object>) v;
            String province = map.get("province").toString();
            String county = map.get("county").toString();


        });

    }
}
